import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "JDBCServlet", value = "/JDBCServlet")
public class JDBCServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/bookshop";

        try {
            //1.加载驱动
            Class.forName(driver);
            //2.建立连接
            conn = DriverManager.getConnection(url,"root","123456");
            String sql = "select * from t_user";
            //3.创建语句对象
            statement = conn.createStatement();
            //4.执行语句
            rs = statement.executeQuery(sql);
            //5.解析结果集
            while (rs.next()){
                String name = rs.getString("username");
                String pass = rs.getString("password");
                int age = rs.getInt(4);
                System.out.println(name+","+pass+","+age);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
